package com.xiaochong.tir.trades.service;

import com.alibaba.fastjson.JSON;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.common.data.hbasepo.TradesHistory;
import com.xiaochong.tir.common.data.hbasepo.TradesHistoryCountFive;
import com.xiaochong.tir.common.data.hbasepo.TradesToKLine;
import com.xiaochong.tir.common.data.mapper.ExchangeInfoMapper;
import com.xiaochong.tir.common.data.mapper.ExchangeTransactionpairMiddleMapper;
import com.xiaochong.tir.common.data.mapper.KLineMapper;
import com.xiaochong.tir.common.data.po.ExchangeInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.po.KLine;
import com.xiaochong.tir.common.data.redisPo.KActionTotalPo;
import com.xiaochong.tir.common.data.vo.ApiCapitalInflowSituationDataVo;
import com.xiaochong.tir.common.data.vo.ApiCapitalInflowSituationVo;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.data.vo.ChartVo;
import com.xiaochong.tir.common.util.*;
import com.xiaochong.tir.trades.component.CnyToUsdRateComponent;
import com.xiaochong.tir.trades.component.HbaseBaseQueryComponent;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.trades.util.AkkaUtilTradesParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.naming.Name;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: 资金净流入计算
 * @Author: org
 * @CreateDate: 2018/7/2 20:01
 */
@Service("kActionQuantizationService")
public class KActionQuantizationService {

    @Autowired
    private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;

    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;
    @Autowired
    private RedisServer rediscConfig;
    @Resource
    private CnyToUsdRateComponent cnyToUsdRateComponent;
    @Autowired
    private ExchangeInfoMapper exchangeInfoMapper;
    @Autowired
    private KLineMapper kLineMapper;

    public void kActionQuantization(int exchangeId){
        LogTrace.info("k线-5、10、1h资金流入-exchangeId","exchangeId",String.valueOf(exchangeId));
        try {
            //查询交易对
            Long st = System.currentTimeMillis();
            ExchangeTransactionpairMiddle exchangeTransactionpairMiddle=new ExchangeTransactionpairMiddle();
            exchangeTransactionpairMiddle.setEnableFlag( true );
            exchangeTransactionpairMiddle.setExchangeId( exchangeId );
            List<ExchangeTransactionpairMiddle> exchangeMiddleList = exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );
            if(exchangeMiddleList != null && exchangeMiddleList.size() > 0){
                //循环处理
                for(ExchangeTransactionpairMiddle middle:exchangeMiddleList){
                    this.capitalInflowSituation(exchangeId,middle.getTransactionName());
                }
            }
            LogTrace.info("k线-5、10、1h资金流入","单个交易所总耗时-"+exchangeId,String.valueOf(System.currentTimeMillis()-st));
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
    }
    public void capitalInflowSituation(Integer exchangeId, String symbol) {
        Long st = System.currentTimeMillis();
        //图标数据
        ChartVo chart3HVo = new ChartVo();
        List<String> x3h = new ArrayList<>();
        List<String> y3h = new ArrayList<>();
        chart3HVo.setX(x3h);
        chart3HVo.setY(y3h);
        ChartVo chart1DVo = new ChartVo();
        List<String> x1d = new ArrayList<>();
        List<String> y1d = new ArrayList<>();
        chart1DVo.setX(x1d);
        chart1DVo.setY(y1d);
        try {
            //获取汇率
            //从redis获取288条数据，循环计算
            String redisKey24HData = RedisKeysUtils.API_SERVICE_TRADES_24H_DATA+"@"+exchangeId+"@"+symbol;
            String redis24HData = rediscConfig.get(redisKey24HData);
            if(StringUtils.isBlank(redis24HData)){
                return;
            }
            List<TradesHistoryCountFive> list24Data = JSON.parseArray(redis24HData,TradesHistoryCountFive.class);
            Map<String,TradesHistoryCountFive> tradesMap = new HashMap<>();
            if(null != list24Data && list24Data.size() > 0){//转成map
                for(int i =0;i<list24Data.size();i++){
                    tradesMap.put(list24Data.get(i).getDateTime(),list24Data.get(i));
                }
            }
            //从redis获取最后一条时间戳，如果没有去服务时间，最后去hbase获取对应条数数据
            //LocalDateTime time = this.getNowLocalDateTime(exchangeId,symbol);
            LocalDateTime time = LocalDateTime.now();
            ApiCapitalInflowSituationVo today = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo fiveMinutes = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo tenMinutes = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo oneHours = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo dayHours = new ApiCapitalInflowSituationVo();
            TradesHistoryCountFive trades = null;
            //time = time.minusDays(1);//当前分钟不要，可能为插入到hbase中
            TradesHistoryCountFive allData = null;
            BigDecimal buyAmount = new BigDecimal(0);
            BigDecimal sellAmount = new BigDecimal(0);
            BigDecimal bugSellAmount = new BigDecimal(0);
            String buyAmountStr = "0";
            String sellAmountStr = "0";
            String bugSellAmountStr = "0";
            int todayDate = time.getDayOfYear();
            int minuCeshi = time.getMinute()/5;
            String ceshiPart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdh);
            ceshiPart += minuCeshi < 10 ? "0"+minuCeshi:minuCeshi;
            LogTrace.infoKvs("资金流入时间段","exchange",exchangeId.toString(),"symbol",symbol,"ceshiPart",ceshiPart);
            String timePart;
            //int oneHourFlag = 0;
           // int tenMinusFlag = 0;
            int todayFlag = 0;
            time = time.minusMinutes(5);
            for(int i=0;i<288;i++){
                //循环288次，共24小时,5分钟一条
                int minu = time.getMinute()/5;
                timePart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdh);
                timePart += minu < 10 ? "0"+minu:minu;
                trades = tradesMap.get(timePart);
                if(trades != null){
                    if(trades.getBuyAmount() == null || trades.getSellAmount() == null || trades.getBuySellAmount() == null
                            || trades.getBuyAmountNew() == null || trades.getSellAmountNew() == null){
                        LogTrace.info("k线-5、10、1h资金流入1error","数据异常",exchangeId+"-"+symbol);
                    }
                    buyAmount = buyAmount.add(trades.getBuyAmount()!=null?trades.getBuyAmount():BigDecimal.ZERO);
                    sellAmount = sellAmount.add(trades.getSellAmount()!=null?trades.getSellAmount():BigDecimal.ZERO);
                    bugSellAmount = bugSellAmount.add(trades.getBuySellAmount()!=null?trades.getBuySellAmount():BigDecimal.ZERO);
                    //老数据问题为空设置0
                    trades.setBuyAmountNew(trades.getBuyAmountNew()!=null?trades.getBuyAmountNew():BigDecimal.ZERO);
                    trades.setSellAmountNew(trades.getSellAmountNew()!=null?trades.getSellAmountNew():BigDecimal.ZERO);
                    buyAmountStr = trades.getBuyAmountNew().setScale(2,BigDecimal.ROUND_DOWN).toString();
                    sellAmountStr = trades.getSellAmountNew().setScale(2,BigDecimal.ROUND_DOWN).toString();
                    bugSellAmountStr = trades.getBuyAmountNew().subtract(trades.getSellAmountNew()).setScale(2,BigDecimal.ROUND_DOWN).toString();
                    //图形插入 3h和1d的
                    if(i < 36){
                        x3h.add(String.valueOf(Timestamp.valueOf(time).getTime()));
                        y3h.add(bugSellAmountStr);
                    }
                    x1d.add(String.valueOf(Timestamp.valueOf(time).getTime()));
                    y1d.add(bugSellAmountStr);
                    //数据和今日,最后一条为今日
                    if(todayFlag ==0){
                        today.setSort("1");
                        today.setTimepart("今日");
                        today.setBuyAmount(buyAmountStr);
                        today.setSellAmount(sellAmountStr);
                        today.setBuySellAmount(bugSellAmountStr);
                        todayFlag++;
                    }
                }
                if(i == 0){ //5分钟
                    fiveMinutes.setSort("2");
                    fiveMinutes.setTimepart("5分钟");
                    fiveMinutes.setBuyAmount(buyAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    fiveMinutes.setSellAmount(sellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    fiveMinutes.setBuySellAmount(bugSellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    fiveMinutes.setTimepartMinus(timePart);
                }
                if(i == 1){//10分钟数据
                    tenMinutes.setSort("3");
                    tenMinutes.setTimepart("10分钟");
                    tenMinutes.setBuyAmount(buyAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    tenMinutes.setSellAmount(sellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    tenMinutes.setBuySellAmount(bugSellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    tenMinutes.setTimepartMinus(timePart);
                }
                if(i == 11){//一小时数据
                    oneHours.setSort("4");
                    oneHours.setTimepart("1小时");
                    oneHours.setBuyAmount(buyAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    oneHours.setSellAmount(sellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    oneHours.setBuySellAmount(bugSellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    oneHours.setTimepartMinus(timePart);
                }
                time = time.minusMinutes(5);
            }
            dayHours.setSort("5");
            dayHours.setTimepart("24小时");
            dayHours.setBuyAmount(buyAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
            dayHours.setSellAmount(sellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
            dayHours.setBuySellAmount(bugSellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
            //计算24小时
            Map<String,ApiCapitalInflowSituationVo> flowMap = new HashMap<>();
            flowMap.put("today",today);
            flowMap.put("fiveMinutes",fiveMinutes);
            flowMap.put("tenMinutes",tenMinutes);
            flowMap.put("oneHours",oneHours);
            flowMap.put("dayHours",dayHours);
            Collections.reverse(x3h);
            Collections.reverse(y3h);
            Collections.reverse(x1d);
            Collections.reverse(y1d);
            //分别插入redis，3h数据，1d数据
            String redisKey3hData= RedisKeysUtils.API_SERVICE_TRADES_3H_DATA+"@"+exchangeId+"@"+symbol;
            String redisKey1dData= RedisKeysUtils.API_SERVICE_TRADES_1D_DATA+"@"+exchangeId+"@"+symbol;
            String redisKey24HCapitalFlow= RedisKeysUtils.API_SERVICE_TRADES_24H_CAPITAL_FLOW_DATA+"@"+exchangeId+"@"+symbol;
            rediscConfig.set(redisKey3hData,JSON.toJSONString(chart3HVo));
            rediscConfig.set(redisKey1dData,JSON.toJSONString(chart1DVo));
            rediscConfig.set(redisKey24HCapitalFlow,flowMap!= null?JSON.toJSONString(flowMap):"");
            LogTrace.info("k线-5、10、1h资金流入","单个耗时",String.valueOf(System.currentTimeMillis()-st));
        }catch (Exception e){
            LogTrace.error("k线-5、10、1h资金流入error",e);
            e.printStackTrace();
        }
    }
    public void capitalInflowSituation2(Integer exchangeId, String symbol) {
        Long st = System.currentTimeMillis();
        //图标数据
        ChartVo chart3HVo = new ChartVo();
        List<String> x3h = new ArrayList<>();
        List<String> y3h = new ArrayList<>();
        chart3HVo.setX(x3h);
        chart3HVo.setY(y3h);
        ChartVo chart1DVo = new ChartVo();
        List<String> x1d = new ArrayList<>();
        List<String> y1d = new ArrayList<>();
        chart1DVo.setX(x1d);
        chart1DVo.setY(y1d);
        try {
            //获取汇率
           /* String rmbUsd = rediscConfig.get(RedisKeysUtils.RMB_USD_RATE);
            if(StringUtils.isBlank(rmbUsd)){
                rmbUsd = cnyToUsdRateComponent.getCnyUsdRate();
            }
            BigDecimal rmbCny = new BigDecimal(rmbUsd);*/
            //从redis获取288条数据，循环计算
            String redisKey24HData = RedisKeysUtils.API_SERVICE_TRADES_24H_DATA+"@"+exchangeId+"@"+symbol;
            String redis24HData = rediscConfig.get(redisKey24HData);
            if(StringUtils.isBlank(redis24HData)){
                return;
            }
            List<TradesHistoryCountFive> list24Data = JSON.parseArray(redis24HData,TradesHistoryCountFive.class);
            Map<String,TradesHistoryCountFive> tradesMap = new HashMap<>();
            if(null != list24Data && list24Data.size() > 0){//转成map
                for(int i =0;i<list24Data.size();i++){
                    tradesMap.put(list24Data.get(i).getDateTime(),list24Data.get(i));
                }
            }
            //从redis获取最后一条时间戳，如果没有去服务时间，最后去hbase获取对应条数数据
            //LocalDateTime time = this.getNowLocalDateTime(exchangeId,symbol);
            LocalDateTime time = LocalDateTime.now();
            ApiCapitalInflowSituationVo today = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo fiveMinutes = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo tenMinutes = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo oneHours = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo dayHours = new ApiCapitalInflowSituationVo();
            TradesHistoryCountFive trades = null;
            time = time.minusMinutes(10);//当前分钟不要，可能为插入到hbase中
            TradesHistoryCountFive allData = null;
            BigDecimal buyAmount = new BigDecimal(0);
            BigDecimal sellAmount = new BigDecimal(0);
            BigDecimal bugSellAmount = new BigDecimal(0);
            int todayDate = time.getDayOfYear();
            int minuCeshi = time.getMinute()/5;
            String ceshiPart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdh);
            ceshiPart += minuCeshi < 10 ? "0"+minuCeshi:minuCeshi;
            LogTrace.infoKvs("资金流入时间段","exchange",exchangeId.toString(),"symbol",symbol,"ceshiPart",ceshiPart);
            String timePart;
            for(int i=0;i<288;i++){
                //循环288次，共24小时,5分钟一条
                int minu = time.getMinute()/5;
                timePart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdh);
                timePart += minu < 10 ? "0"+minu:minu;
                trades = tradesMap.get(timePart);
                if(trades != null){
                    buyAmount = buyAmount.add(trades.getBuyAmount());
                    sellAmount = sellAmount.add(trades.getSellAmount());
                    bugSellAmount = buyAmount.subtract(sellAmount);
                    dayHours.setSellAmount(sellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    dayHours.setBuySellAmount(bugSellAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    dayHours.setBuyAmount(buyAmount.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    //图形插入 3h和1d的
                    BigDecimal flow = trades.getBuyAmount().subtract(trades.getSellAmount());
                    if(i < 36){
                        x3h.add(String.valueOf(Timestamp.valueOf(time).getTime()));
                        y3h.add(flow.setScale(2,BigDecimal.ROUND_DOWN).toString());
                    }
                    x1d.add(String.valueOf(Timestamp.valueOf(time).getTime()));
                    y1d.add(flow.setScale(2,BigDecimal.ROUND_DOWN).toString());

                }
                if(i == 0){//5分钟数据
                    fiveMinutes.setSort("2");
                    fiveMinutes.setTimepart("5分钟");
                    fiveMinutes.setBuyAmount(dayHours.getBuyAmount());
                    fiveMinutes.setSellAmount(dayHours.getSellAmount());
                    fiveMinutes.setBuySellAmount(dayHours.getBuySellAmount());
                    fiveMinutes.setTimepartMinus(timePart);
                }else if(i == 1){//10分钟数据
                    tenMinutes.setSort("3");
                    tenMinutes.setTimepart("10分钟");
                    tenMinutes.setBuyAmount(dayHours.getBuyAmount());
                    tenMinutes.setSellAmount(dayHours.getSellAmount());
                    tenMinutes.setBuySellAmount(dayHours.getBuySellAmount());
                    tenMinutes.setTimepartMinus(timePart);
                }else if(i == 11){//一小时数据
                    oneHours.setSort("4");
                    oneHours.setTimepart("1小时");
                    oneHours.setBuyAmount(dayHours.getBuyAmount());
                    oneHours.setSellAmount(dayHours.getSellAmount());
                    oneHours.setBuySellAmount(dayHours.getBuySellAmount());
                    oneHours.setTimepartMinus(timePart);
                }
                time = time.minusMinutes(5);
                //今日
                int nowDay = time.getDayOfYear();
                if(todayDate != nowDay){
                    today.setSort("1");
                    today.setTimepart("今日");
                    today.setBuyAmount(dayHours.getBuyAmount());
                    today.setSellAmount(dayHours.getSellAmount());
                    today.setBuySellAmount(dayHours.getBuySellAmount());
                    todayDate = nowDay;//防止第二次进入
                }
            }
            //计算24小时
            dayHours.setSort("5");
            dayHours.setTimepart("24小时");
            Map<String,ApiCapitalInflowSituationVo> flowMap = new HashMap<>();
            flowMap.put("today",today);
            flowMap.put("fiveMinutes",fiveMinutes);
            flowMap.put("tenMinutes",tenMinutes);
            flowMap.put("oneHours",oneHours);
            flowMap.put("dayHours",dayHours);
            /*Collections.reverse(x3h);
            Collections.reverse(y3h);
            Collections.reverse(x1d);
            Collections.reverse(y1d);*/
            //分别插入redis，3h数据，1d数据
            String redisKey3hData= RedisKeysUtils.API_SERVICE_TRADES_3H_DATA+"@"+exchangeId+"@"+symbol;
            String redisKey1dData= RedisKeysUtils.API_SERVICE_TRADES_1D_DATA+"@"+exchangeId+"@"+symbol;
            String redisKey24HCapitalFlow= RedisKeysUtils.API_SERVICE_TRADES_24H_CAPITAL_FLOW_DATA+"@"+exchangeId+"@"+symbol;
            rediscConfig.set(redisKey3hData,JSON.toJSONString(chart3HVo));
            rediscConfig.set(redisKey1dData,JSON.toJSONString(chart1DVo));
            rediscConfig.set(redisKey24HCapitalFlow,flowMap!= null?JSON.toJSONString(flowMap):"");
            LogTrace.info("k线-5、10、1h资金流入","单个耗时",String.valueOf(System.currentTimeMillis()-st));
        }catch (Exception e){
            LogTrace.error("k线-5、10、1h资金流入",e);
            e.printStackTrace();
        }
    }

    public LocalDateTime getNowLocalDateTime(int exchangeId,String symbol){
        //从redis获取最后一条时间戳，如果没有去服务时间，最后去hbase获取对应条数数据
        String redisData = rediscConfig.get(RedisKeysUtils.API_SERVICE_TRADES+"@"+exchangeId+"@"+symbol);
        Long lastTimestamp = Long.MIN_VALUE;
        //获取redis中最大时间戳，后面去重使用
        if(StringUtils.isNotBlank(redisData)){
            List<TradesHistory> tradesRedisList = JSON.parseArray(redisData,TradesHistory.class);
            if(tradesRedisList != null && tradesRedisList.size() > 0){
                lastTimestamp = tradesRedisList.get(tradesRedisList.size()-1).getTimestamp();
            }
        }
        if(lastTimestamp == Long.MIN_VALUE){ //获取服务器当前时间
            lastTimestamp = System.currentTimeMillis();
        }
        LocalDateTime time = DateUtils.getDateTimeOfTimestamp(lastTimestamp);
        return time;
    }

    /**
     *计算24小时k线最高价、最低价、交易量
     */
    public void calculateKActionHighAndLowVolume() {
        try {
            //查询交易所-交易对列表
            ExchangeInfo exchangeInfo=new ExchangeInfo();
            exchangeInfo.setEnableFlag( true );
            exchangeInfo.setDeleteFlag( false );
            exchangeInfo.setKlineStatus( true );
            List<ExchangeInfo> infoList=exchangeInfoMapper.selectByEntityList( exchangeInfo );
            LocalDateTime time = LocalDateTime.now();
            //获取汇率
           /* String rmbUsd = rediscConfig.get(RedisKeysUtils.RMB_USD_RATE);
            if(StringUtils.isBlank(rmbUsd)){
                rmbUsd = cnyToUsdRateComponent.getCnyUsdRate();
            }
            BigDecimal rmbCny = new BigDecimal(rmbUsd)*/;
            for(ExchangeInfo exchange : infoList){
                //获取交易对
                ExchangeTransactionpairMiddle exchangeTransactionpairMiddle=new ExchangeTransactionpairMiddle();
                exchangeTransactionpairMiddle.setEnableFlag( true );
                exchangeTransactionpairMiddle.setExchangeId(exchange.getId());

                List<ExchangeTransactionpairMiddle> exchangeMiddleList = exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );
                if(exchangeMiddleList != null && exchangeMiddleList.size() > 0){
                    for(ExchangeTransactionpairMiddle middle:exchangeMiddleList){
                        /*if(12 == exchange.getId()){
                            System.out.println(middle.getTransactionName());
                        }*/
                        BigDecimal maxPrice = new BigDecimal(0);
                        BigDecimal minPrice = new BigDecimal(0);
                        BigDecimal totalVolume = new BigDecimal(0);
                        //循环处理,查询24小时内的最高、最低、交易量放入缓存中
                        LocalDateTime nowTime = time.minusMinutes(0);
                        for(int i =0;i<24;i++){
                            String lastRowKey = DateUtils.localDateTimeFormatString(nowTime,DateUtils.format_ymdh);//当前时间转成分钟
                            String rowKey = HbaseTableUtils.K_ACTION_K_LINE_ROW_KEY_1H+"@"+exchange.getId()+"@"+middle.getTransactionName()+"@"+lastRowKey;
                            Map<String, Object> hbaseData = hbaseBaseQueryComponent.selectData(HbaseTableUtils.CURRENCY_INFO_K_LINE_TABLE_NAME
                                    , rowKey);
                            if(null != hbaseData && hbaseData.get("volume") != null && hbaseData.get("highestPrice") != null && hbaseData.get("lowestPrice") != null){
                                BigDecimal volume = new BigDecimal(hbaseData.get("volume").toString());
                                BigDecimal highOpen = new BigDecimal(hbaseData.get("highestPrice").toString());
                                BigDecimal lowClose = new BigDecimal(hbaseData.get("lowestPrice").toString());
                                totalVolume = totalVolume.add(volume);

                                if(maxPrice.compareTo(highOpen) < 0){
                                    maxPrice = highOpen;
                                }
                                if(minPrice.compareTo(BigDecimal.valueOf(0)) ==0){
                                    minPrice = lowClose;
                                }else {
                                    if(minPrice.compareTo(lowClose) > 0){
                                        minPrice = lowClose;
                                    }
                                }
                            }
                             nowTime = nowTime.minusHours(1);
                        }
                        //保存redis中
                        KActionTotalPo kActionTotalPo = new KActionTotalPo();
                        kActionTotalPo.setAmount(totalVolume.setScale(2,BigDecimal.ROUND_DOWN).toString());
                        kActionTotalPo.setMinPrice24H(this.conversionPrice(exchange.getId(),middle.getTransactionName(),minPrice));
                        kActionTotalPo.setMaxPrice24H(this.conversionPrice(exchange.getId(),middle.getTransactionName(),maxPrice));
                        kActionTotalPo.setTimeLong(System.currentTimeMillis());
                        String redis24HKey = RedisKeysUtils.API_SERVICE_TRADES_24H_MAX_MIN_PRICE_VOLUME+"@"+exchange.getId()+"@"+middle.getTransactionName();
                        //将昨日收盘插入到当前redis中
                        String redisKey= RedisKeysUtils.API_SERVICE_TRADES_PRIOD_YESTERDAY+"@"+exchange.getId()+"@"+middle.getTransactionName();
                        String data= rediscConfig.get(redisKey);
                        //LogTrace.info("行情k线","获取昨日收盘数据耗时",String.valueOf(System.currentTimeMillis()- ss));
                        if(StringUtils.isNotBlank(data)){
                            KActionTotalPo kActionTotalPoYes =  JSON.parseObject(data,KActionTotalPo.class);
                            if(null != kActionTotalPoYes && StringUtils.isNotBlank(kActionTotalPoYes.getYesterdayClosePriceCny())){
                                //BigDecimal lastPriceB = StringUtils.isNotBlank(kActionTotalPoYes.getYesterdayClosePriceCny())?new BigDecimal(kActionTotalPoYes.getYesterdayClosePriceCny()).setScale(2,BigDecimal.ROUND_DOWN):BigDecimal.valueOf(0);
                                kActionTotalPo.setYesterdayClosePriceCny(kActionTotalPoYes.getYesterdayClosePriceCny());
                            }
                        }
                        rediscConfig.set(redis24HKey,JSON.toJSONString(kActionTotalPo));
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("K线-24小时最高最低价格、成交量",e);
        }
    }
    /**
     * 平台币或者非usd和usdt结尾的交易对转成美金交易对，最后转成人民币价格
     * @param exchangeId
     * @param symbol
     * @param price
     * @return
     */
    private String conversionPrice(Integer exchangeId, String symbol, BigDecimal price) {
        String [] sy = symbol.split("/");
        //美元获取汇率
        String rmbUsd = rediscConfig.get(RedisKeysUtils.RMB_USD_RATE);
        if(StringUtils.isBlank(rmbUsd)){
            rmbUsd = cnyToUsdRateComponent.getCnyUsdRate();
        }
        BigDecimal rmbUsdToCny = new BigDecimal(rmbUsd);
        String baseCoin = sy[1];
        baseCoin = baseCoin.toUpperCase();
        if(!"CNY".equals(baseCoin)){
            if(!"USD".equals(baseCoin) || !"USDT".equals(baseCoin)){//查找到对应的usdt或者usd价格
                String[] searchCoin = {baseCoin+"/USDT",baseCoin+"/USD"};
                LocalDateTime time = LocalDateTime.now();
                int i = 0;
                String converPrice = "";
                Integer exchangeIdConvert = rediscConfig.get(RedisKeyApp.EXCHANGE_PING_TAI_B_CONVERT+exchangeId,Integer.class);
                if(exchangeIdConvert != null){
                    exchangeId =exchangeIdConvert;
                }
                for(String coin :searchCoin){
                    String changeRedisKey = RedisKeysUtils.API_SERVICE_K_ACTION_ALL_DATA_PRICE+"@"+exchangeId+"@"+coin;
                    String data = rediscConfig.get(changeRedisKey);
                    KActionTotalPo kActionTotalPo = JSON.parseObject(data,KActionTotalPo.class);
                    if(kActionTotalPo != null){
                        converPrice = kActionTotalPo.getLastOpenPrice();
                        break;
                    }
                }
                if(StringUtils.isNotBlank(converPrice)){
                    BigDecimal conPrice = new BigDecimal(converPrice);
                    price = price.multiply(conPrice);
                }
            }
            price = price.multiply(rmbUsdToCny);
        }
        return price.toString();
    }
    /**
     * 从reids获取昨日收盘价格
     */
    public void calculateYesterdayClosePriceInit() {
        try {
            //查询交易所-交易对列表
            /*ExchangeInfo exchangeInfo=new ExchangeInfo();
            exchangeInfo.setEnableFlag( true );
            exchangeInfo.setDeleteFlag( false );
            exchangeInfo.setKlineStatus( true );
            List<ExchangeInfo> infoList=exchangeInfoMapper.selectByEntityList( exchangeInfo )*/;
            LocalDateTime time = LocalDateTime.now();
            BigDecimal closePrice = new BigDecimal(0);
            KActionTotalPo kActionTotalPo ;
            String yesterdayData;
            //获取汇率
            /*String rmbUsd = rediscConfig.get(RedisKeysUtils.RMB_USD_RATE);
            if(StringUtils.isBlank(rmbUsd)){
                rmbUsd = cnyToUsdRateComponent.getCnyUsdRate();
            }
            BigDecimal rmbCny = new BigDecimal(rmbUsd);*/
            //循环处理,查询昨日价格放入缓存中，主要使用昨日收盘价格，也是昨日最后一条数据
            LocalDateTime nowTime = time.minusDays(1);
            String lastStr = DateUtils.localDateTimeFormatString(nowTime,DateUtils.format_ymd);//当前时间转成分钟
            //查询昨日所有日k数据放入缓存中，并且根据汇率计算出人民币价格
            KLine kLine = new KLine();
            kLine.setKType(KLineTypeEnum.DAY.getIndex().toString());
            kLine.setKDate(lastStr);
          //  kLine.setExchangeId(exchange.getId());
           // kLine.setTransationPairName(middle.getTransactionName());
            List<KLine> kLineData = kLineMapper.selectByEntityList(kLine);
            if(kLineData != null && kLineData.size() > 0){
                for(KLine line :kLineData){
                    closePrice = new BigDecimal(line.getClosePrice());
                    kActionTotalPo = new KActionTotalPo();
                    kActionTotalPo.setYesterdayClosePrice(closePrice.toString());
                    kActionTotalPo.setYesterdayClosePriceCny(this.conversionPrice(line.getExchangeId(),line.getTransationPairName(),closePrice));
                    kActionTotalPo.setTimeLong(System.currentTimeMillis());
                    yesterdayData= RedisKeysUtils.API_SERVICE_TRADES_PRIOD_YESTERDAY+"@"+line.getExchangeId()+"@"+line.getTransationPairName();
                    rediscConfig.set(yesterdayData,JSON.toJSONString(kActionTotalPo));
                }
            }
            /*for(ExchangeInfo exchange : infoList){
                //获取交易对
                ExchangeTransactionpairMiddle exchangeTransactionpairMiddle=new ExchangeTransactionpairMiddle();
                exchangeTransactionpairMiddle.setEnableFlag( true );
                exchangeTransactionpairMiddle.setExchangeId(exchange.getId());
                List<ExchangeTransactionpairMiddle> exchangeMiddleList = exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );
                if(exchangeMiddleList != null && exchangeMiddleList.size() > 0){
                    for(ExchangeTransactionpairMiddle middle:exchangeMiddleList){
                        if(12 == exchange.getId()){
                            System.out.println(middle.getTransactionName());
                        }


                    }
                }
            }*/

        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("从redis获取昨日收盘价格",e);
        }
    }

}
